// pages/register/register.js
const db = wx.cloud.database();
const dbUser = db.collection("user")
Page({
  data: {
    schools: ['大塘校区', '韩家山校区', '黄田坝校区'],
    school: '请选择所属校区',
    type: '',
  },
  // 选择
  checkRadio(e) {
    console.log(e.detail.value)
    this.setData({
      type: e.detail.value
    })
  },
  //选择校区
  bindSchoolChange(e) {
    this.setData({
      school: this.data.schools[e.detail.value]
    })
  },
  reg(e) {
    let user = e.detail.value
    console.log('user', user)
    if (!user || !user.type) {
      wx.showToast({
        icon: 'error',
        title: '请选择身份',
      })
    } else if (user.school == '请选择所属校区') {
      wx.showToast({
        icon: 'error',
        title: '请选择所属校区',
      })
    } else if (!user.phone) {
      wx.showToast({
        icon: 'error',
        title: '请填写手机',
      })
    } else if (!user.password) {
      wx.showToast({
        icon: 'error',
        title: '请填写密码',
      })
    } else if (!user.name) {
      wx.showToast({
        icon: 'error',
        title: '请填写姓名',
      })
    } else if (!user.department) {
      wx.showToast({
        icon: 'error',
        title: '请填写系别',
      })
    } else if (user.type == '学生' && (!user.class)) {
      wx.showToast({
        icon: 'error',
        title: '请填写年级',
      })
    } else if (user.type == '教职' && (!user.teachclass)) {
      wx.showToast({
        icon: 'error',
        title: '请填写授课班级',
      })
    } else {
      dbUser.doc(user.phone).get()
        .then(res => {
          console.log('查询结果', res)
          if (res.data) {
            wx.showToast({
              icon: 'error',
              title: '手机号已注册过',
              duration: 2500
            })
          } else {
            this.addUser(user)
          }
        }).catch(res => {
          console.log('没有注册过')
          this.addUser(user)
        })
    }
  },
  addUser(user) {
    user._id = user.phone
    user.status = '待审核'
    dbUser.add({
      data: user
    }).then(res => {
      console.log('注册成功', res)
      wx.showToast({
        title: '注册成功！',
        icon: 'success',
        duration: 2500
      })
      setTimeout(function () {
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }, 2000)
    })
  }
})